package 反射4;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflection {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
//        不使用反射
        Teacher teacher = new Teacher();
        String typeInstanceOf = getTypeInstanceOf(teacher);
        System.out.println("typeInstanceOf = " + typeInstanceOf);
//        测试反射方式
        Student student = new Student();
        String type = getType(student);
        System.out.println("type = " + type);
    }

    /**
     *
     * @param obj
     * @return
     */
    public static String getTypeInstanceOf(Object obj){
        //学生
        if(obj instanceof Student){
            Student student = (Student) obj;
            String userType = student.getUserType("王小明");
            return userType;
        }
        if(obj instanceof Teacher){
            Teacher teacher = (Teacher) obj;
            String userType = teacher.getUserType("王笑笑");
            return userType;
        }
        return null;
    }

    /**
     * 通过反射获取用户的类型
     * @param obj
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static String getType(Object obj) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> aClass = obj.getClass();
        Object o = aClass.newInstance();
        Method getUserType = aClass.getMethod("getUserType", String.class);
        String invoke = (String) getUserType.invoke(o,"王小明");
        return invoke;
    }
    /**
     * 我好像悟了，就是第二个方法在编译时是不知道对象类型的
     * 运行阶段、动态获取
     */
}
